﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace OGS.Utility
{
    //Customized data annotation validator for uploading file
    public class ValidateImageFileAttribute : ValidationAttribute
    {
        /// <summary>
        /// Check if upload file is valid or not
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public override bool IsValid(object value)
        {
            int MaxContentLength = 1024 * 1024 / 10; //100KB
            string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".jpeg" };

            var file = value as HttpPostedFileBase;

            if (file == null)
            {
                return true;
            }
            else if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
            {
                ErrorMessage = "Please upload image of type: " + string.Join(", ", AllowedFileExtensions) + ".";
                return false;
            }
            else if (file.ContentLength > MaxContentLength)
            {
                ErrorMessage = "Your image is too large, maximum allowed size is : " + (MaxContentLength).ToString() + "KB.";
                return false;
            }
            else
                return true;
        }
    }
}